package com.braveman.im.utils;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Created by xuebo li on 2016/12/30.
 */

public class ViewUtils {

    /**
     * 向textView添加drawable
     *
     * @param textView   被添加的TextView
     * @param drawableId 图片的资源id
     * @param where      1 2 3 4 对应 左 上 右 下
     */
    public static void addDrawable2TvById(TextView textView, int drawableId, int where) {
        textView.setCompoundDrawablesWithIntrinsicBounds(where == 1 ? drawableId : 0, where == 2 ? drawableId : 0, where == 3 ? drawableId : 0, where == 4 ? drawableId : 0);
    }

    // private static final int DECIMAL_DIGITS = 1;//小数的位数

    //设置editText 小数点保留两位
    public static void setPoint(final EditText editText, final int decimalDigits) {//decimalDigits 小数点 后几位
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > decimalDigits) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + decimalDigits + 1);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

}
